package com.team9.fitness.service;

import com.team9.fitness.entity.PostComment;
import com.team9.fitness.mapper.PostCommentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 帖子评论服务类
 * 
 * 提供帖子评论相关的业务逻辑：
 * - 评论管理：创建、更新、删除评论
 * - 查询功能：支持按帖子、用户、ID查询，支持排序
 * - 统计功能：统计评论的点赞数量
 * - 状态管理：支持用户点赞状态查询
 */
@Service
@Transactional
@Slf4j
public class PostCommentService {

    @Autowired
    private PostCommentMapper postCommentMapper;

    /**
     * 创建评论
     */
    public PostComment createComment(PostComment comment) {
        log.info("创建帖子评论: postId={}, userId={}", comment.getPostId(), comment.getUserId());

        // 初始化统计字段
        comment.initializeCounts();
        comment.setCreatedAtIfNull();

        postCommentMapper.insert(comment);
        log.info("创建帖子评论成功: id={}", comment.getId());

        return comment;
    }

    /**
     * 根据帖子ID获取评论列表（包含统计信息）
     */
    public List<PostComment> getCommentsByPostId(Long postId, Long currentUserId) {
        log.info("获取帖子评论: postId={}, currentUserId={}", postId, currentUserId);
        return postCommentMapper.selectByPostIdWithStatsOrderByCreatedAtAsc(postId, currentUserId);
    }

    /**
     * 根据用户ID获取评论列表（包含统计信息）
     */
    public List<PostComment> getCommentsByUserId(Long userId, Long currentUserId) {
        log.info("获取用户评论: userId={}, currentUserId={}", userId, currentUserId);
        return postCommentMapper.selectByUserIdWithStatsOrderByCreatedAtDesc(userId, currentUserId);
    }

    /**
     * 根据ID获取评论（包含统计信息）
     */
    public Optional<PostComment> getCommentById(Long id, Long currentUserId) {
        log.info("根据ID获取评论: id={}, currentUserId={}", id, currentUserId);
        return postCommentMapper.selectByIdWithStats(id, currentUserId);
    }

    /**
     * 更新评论
     */
    public PostComment updateComment(PostComment comment) {
        log.info("更新评论: id={}", comment.getId());

        postCommentMapper.updateById(comment);
        log.info("更新评论成功: id={}", comment.getId());

        return comment;
    }

    /**
     * 删除评论
     */
    public void deleteComment(Long id) {
        log.info("删除评论: id={}", id);
        postCommentMapper.deleteById(id);
        log.info("删除评论成功: id={}", id);
    }

    /**
     * 添加评论业务逻辑（供ZRDDS调用）
     */
    public PostComment addCommentByZRDDS(Long userId, Long postId, String content) {
        try {
            log.info("添加评论: userId={}, postId={}", userId, postId);

            PostComment comment = new PostComment();
            comment.setUserId(userId);
            comment.setPostId(postId);
            comment.setContent(content);
            comment.initializeCounts();
            comment.setCreatedAtIfNull();

            postCommentMapper.insert(comment);
            log.info("添加评论成功: id={}", comment.getId());

            return comment;
        } catch (Exception e) {
            log.error("添加评论失败: userId={}, postId={}", userId, postId, e);
            return null;
        }
    }

    /**
     * 更新评论点赞数量
     */
    public void updateCommentLikeCount(Long commentId, Integer likeCount) {
        try {
            postCommentMapper.updateLikeCount(commentId, likeCount);
            log.debug("更新评论点赞数量: commentId={}, likeCount={}", commentId, likeCount);
        } catch (Exception e) {
            log.error("更新评论点赞数量失败: commentId={}, likeCount={}", commentId, likeCount, e);
        }
    }
}
